import { api, useAxiosResponse } from '@/api'
import { bwUtilsCookie } from '@/utils'
// import { getAppEnvConfig } from '@/utils/env'

import { BwCacheEnum } from '@/enums/cacheEnum'

import type { SysTokenAppInfoOutput } from '@bitwit/tenantapi'

/** 提前刷新时间 */
const beforeTime = 360000
/** 定时器 */
let timer: Nullable<NodeJS.Timeout> = null

/** 注册计时器 */
function onSetTimeout(time: number) {
  onClearTimeout()
  timer = setTimeout(() => {
    const curTime = Date.now()
    const curExpiresIn = bwUtilsCookie.getCookie(BwCacheEnum.expiresIn)
    const refreshTime = Number(curExpiresIn) - curTime
    if (refreshTime <= beforeTime) {
      onRefreshToken()
        .then((time) => {
          onSetTimeout(time)
        })
        .catch((error) => {
          alert(error)
          toLoginPage()
        })
    } else {
      onSetTimeout(time)
    }
  }, time)
}

/** 清除计时器 */
function onClearTimeout() {
  timer && clearTimeout(timer)
  timer = null
}

/** 返回登录页 */
export function toLoginPage() {
  // const otherWindow = window?.parent
  // const { VITE_APP_Micro_Apps_Page_Render } = getAppEnvConfig()
  // const href = `${VITE_APP_Micro_Apps_Page_Render}/login`
  // otherWindow
  //   ? (otherWindow.location.href = href)
  //   : (window.location.href = href)
}

/** 刷新token */
export function onRefreshToken() {
  return new Promise<number>((resolve, reject) => {
    const curRToken = bwUtilsCookie.getCookie(BwCacheEnum.refreshToken)
    if (curRToken) {
      api
        .apiSysTokenRefreshGet(curRToken)
        .then((res) => {
          const resData = useAxiosResponse<SysTokenAppInfoOutput>(res)

          const newToeken = resData?.accessToken ?? ''
          const newExpiresIn = resData?.expiresIn ?? ''
          const newRefreshToken = resData?.refreshToken ?? ''

          if (newToeken && newExpiresIn && newRefreshToken) {
            const newTime = Number(newExpiresIn) * 1000
            const newExpiresInData = Date.now() + newTime

            bwUtilsCookie.setCookie(BwCacheEnum.token, newToeken, {})
            bwUtilsCookie.setCookie(
              BwCacheEnum.refreshToken,
              newRefreshToken,
              {}
            )
            bwUtilsCookie.setCookie(
              BwCacheEnum.expiresIn,
              newExpiresInData?.toString(),
              {}
            )
            resolve(newTime)
          } else {
            reject('刷新Token失败,请重新登录!')
          }
        })
        .catch((err) => {
          console.error(err)
          reject('登录过期,请重新登录!')
        })
    } else {
      reject('没有获取到token刷新秘钥,请重新登录！')
    }
  })
}

/** 设置 token 刷新计时器 */
export function onSetRefreshTokenTimeout() {
  const curTime = Date.now()
  /** 随机1-5分钟时间,避免多个定时器同时刷新请求 */
  const randomTime = Math.floor(Math.random() * 30000)
  const curExpiresIn = bwUtilsCookie.getCookie(BwCacheEnum.expiresIn) ?? 0

  const time = Number(curExpiresIn) - curTime - beforeTime + randomTime
  onSetTimeout(time)
}
